<?php
// +----------------------------------------------------------------------
// | Date:2016年12月26日
// +----------------------------------------------------------------------
// | Author: EK_熊<1439527494@qq.com>
// +----------------------------------------------------------------------
// | Description: 此文件作用于****
// +----------------------------------------------------------------------
namespace Admin\Controller;
use Think\Controller;
class ProductController extends CommonController {
    protected $model;
    protected $recommend_type = ['0'=>'未推荐','1'=>'精选','2'=>'经典','3'=>'洞察'];
    public function _initialize(){
        parent::_initialize();
        $this->model=M('Product');
        $this->curd_call_back='callback';
        $this->assign('recommend_type',$this->recommend_type);
    }
    
    
    /**
     * 作品首页列表
     * 
     * date:2016年12月19日
     * author: EK_熊
     */
    public function index() {
        $where = [];
        $groupId = I('group_id');
        $title = I('title');
        $proid = I('proid');
        $t_lx = I('t_lx');
        $update_num = I('update_num');
        $recommend_type = I('recommend_type');
        
        $order='listorder DESC, id DESC';
        
        if ($title)        $where['title'] = ['like',"%$title%"];
        if ($recommend_type >0) $where['recommend_type'] = $recommend_type;
        if ($t_lx)         $where['t_lx'] = $t_lx;
        if ($proid)        $where['id'] = $proid;
        if ($groupId)      $where['group_id'] = $groupId;
        if ($update_num)   {
            $where['update_num'] = $update_num;
            if ($update_num == 6) $where['update_num'] = ['gt',5];
            if ($update_num == 7) $where['update_num'] = 0;
        }
        
        $list = $this->lists($this->model,$where,$order);
        
        $catlist = M('category')->where(['pid'=>0])->order('listorder')->getField('cid,name',true);
        
        $this->assign('catlist',$catlist);
        $this->assign('list',$list);
        $this->display();
    }
    
    /**
     * 推荐经典到首页
     *
     * date:2016年12月19日
     * author: EK_熊
     */
    public function setRecommend(){
        $model = empty($model) ? $this->model : $model;
        $id = I('id');
        $type = I('type');
        $value = I('value');
        $typeBox = [
            '1'=>'is_recommend',
            '2'=>'is_classics',
            '3'=>'is_dx'
        ];
        $ret = $model->where(['id'=>$id])->save(["$typeBox[$type]"=>$value,'update_time'=>time()]);
        if (!$ret) {
            $this->error('网络异常，操作失败！');
        }
        $this->success('操作完成！');
    }    
    
    
    
    
    private function _category_country(){
        $ret = F('category_country');
        if (!$ret) {
            
            $ret = M('category')->where(['pid'=>3])->order('listorder')->field('cid as value,name as label,name as value,pid')->select();
            $ret = json_encode($ret);
            F('category_country',$ret);
        }
        return $ret;
    }
    
    
    /**
     * 作品发布配置管理
     * 
     * date:2016年12月23日
     * author: EK_熊
     */
    public function config(){
        
        $key = 'pro_index';
        $configModel = D('Config');
        if (IS_POST) {
            $post = I('post');
            $setConfig = $configModel->setConfig($key,$post);
            if (!$setConfig) $this->error('网络异常，操作失败！');
            $this->success('操作完成！');
        }
        $config = $configModel->getConfig($key);
        $this->assign('config',$config);
        $this->display();
        
    }
    
    /**
     * 创建添加系列
     * 
     * date:2016年12月23日
     * author: EK_熊
     */
    public function createGroup(){
        $ids = I('ids');
        $groupName = I('groupname');
        if (count($ids) < 2) $this->error('请至少选择两个作品');
        if (empty($groupName)) $this->error('请输入系列名称');
        
        /*添加 系列数据*/
        $proGroupModel = M('ProductGroup');
        $isExist = $proGroupModel->where(['grp_name'=>$groupName])->find();
        if ($isExist) $this->error('该名称已经存在！');
        
        do{
            $errMsg = '';
            $proGroupModel->startTrans();
            
            $grpId = $proGroupModel->add([
                'grp_name'=>$groupName,
                'created_time'=>CURRENT_TIME,
                'total'=>count($ids),
            ]);
            
            if (!$grpId) {
                $errMsg = '网络异常，系列数据添加错误！'; 
                break;
            }
            
            /*更新作品group_id*/
            $updatePro = $this->model->where(['id'=>['in',$ids]])->save(['group_id'=>$grpId]);
            if (!$updatePro) {
                $errMsg = '网络异常，作品系列id更新错误！'; 
                break;
            }
        }while(false);
        
        if (!empty($errMsg)) {
            $proGroupModel->rollback();
            $this->error($errMsg);
        }else{
            $proGroupModel->commit();
            $this->success('操作执行成功！');
        }
        
    }
    
    
    /**
     * 添加作品至该系列
     * 
     * date:2017年3月24日
     * author: EK_熊
     */
    public function  addtoGroup(){
        $ids = I('ids');
        $groupId = I('groupid');
        if (count($ids) < 1) $this->error('请至少选择1个作品');
        if (empty($groupId)) $this->error('请输入系列id');
        $ret = D('ProductGroup')->group_add_product($ids,$groupId);//往系列里面添加作品
        if(!$ret) $this->error('网络异常，添加失败！');
        $this->success('操作完成！');
    }
    
    
    /**
     * 系列作品管理，数据页面
     * 
     * date:2016年12月23日
     * author: EK_熊
     */
    public function group(){
        $proGroupModel = D('ProductGroup');
        if (IS_POST) {
            $value = I('value');
            $idAry = I('ids');
            $grp_id = $idAry[0];
            switch (I('action')){
                case 'grp_name' : 
                       $ret = $proGroupModel->group_set_name($grp_id,$value);//修改系列名称
                       break;
                case 'productID':  
                       $proId = explode(',',$value);
                       $ret = $proGroupModel->group_add_product($proId,$grp_id);//往系列里面添加作品
                       break;
            }
            
            if (!$ret) $this->error($proGroupModel->getError());
            $this->success('操作完成！！');
        }
        $list = $this->lists($proGroupModel,$where=[],$order='grp_id DESC');
        $this->assign('list',$list);
        $this->display();
    }
    
    
    /**
     * 查看系列下面的作品，弹窗显示
     * 
     * date:2016年12月26日
     * author: EK_熊
     */
    public function groupProList(){
        
        $where['group_id'] = I('group_id');
        
        $list = $this->lists($this->model,$where,$order='');
        $this->assign('list',$list);
        $this->display();
        
    }
    
    public function groupRemove($proid){
        $ret = $this->model->where(['id'=>$proid])->setField('group_id',null);
        if (!$ret) $this->error('操作失败！');
        $this->success('操作完成！');
    }

    /**
     * 系列作品管理：删除
     * 
     * date:2016年12月23日
     * author: EK_熊
     */
    public function groupDel(){
        M('product')->where(['group_id'=>['in',I('ids')]])->save(['group_id'=>'']);
        parent::delete(M('ProductGroup'));
    }
    
    
    public function add() { 
        if (IS_POST) {
//             $this->checkToken();
            
           $this->ajaxReturn(D("Product")->addProduct());
        } else {
            $cate = array();
            $list = D("Product")->category();
            foreach ($list as $item) {
                $cate[$item["pid"]] ? $cate[$item["pid"]] : $cate[$item["pid"]]= array();
                array_push($cate[$item["pid"]], $item);
            }
            $this->assign('cate_country',$this->_category_country());
            $this->assign("list", $list);
            $this->display();
        }
    }

    public function checkProductTitle() {
        $M = M("Product");
        if(!$_GET['title']){
            $this->ajaxReturn(array("status" => 0, "info" => "标题为空"));
        }
        $where = "title='" . I('get.title') . "'";
        if (!empty($_GET['id'])) {
            $where.=" And id !=" . (int) $_GET['id'];
        }
        if(!I('get.title')){
            $this->ajaxReturn(array("status" => 0, "info" => "请输入标题"));
        }
        if ($M->where($where)->count() > 0) {
            $this->ajaxReturn(array("status" => 0, "info" => "已经存在，请修改标题"));
        } else {
            $this->ajaxReturn(array("status" => 1, "info" => "可以使用"));
        }
    }

    public function edit() {
        $M = M("Product");
        if (IS_POST) {
//             $this->checkToken();
            $this->ajaxReturn(D("Product")->edit());
        } else {
            $info = $M->where("id=" . (int) $_GET['id'])->find();
            if ($info['id'] == '') {
                $this->error("不存在该记录");
            }
            if($info['image_id']){
                $image = M("images");
                $map['id']=array('in',$info['image_id']);
                $img_info = $image->where($map)->order('id asc')->select();
                $this->assign("img_info", $img_info);
            }
            if ($info['t_gj']) $info['t_gj'] = M('Category')->where('cid='.$info['t_gj'])->getField('name');
            $this->assign("info", $info);
            $this->assign('cate_country',$this->_category_country());
            $this->assign("videos",explode(",",$info["media_id"]));
            $this->assign("awards",explode(",",$info["t_jx"]));
            // var_dump(explode(",",$info["t_jx"]));
            $this->display("add");
        }
    }

    public function del() {
        if (M("Product")->where("id=" . (int) $_GET['id'])->delete()) {
            $this->ajaxReturn(array("status" => 1, "info" =>'删除成功'));
//            $this->ajaxReturn(array("status"=>1,"info"=>""));
        } else {
            $this->ajaxReturn(array("status" => 0, "info" =>'删除失败，可能是不存在该ID的记录'));
        }
    }
    
    


    


    public function changeStatus(){
        $id=I('get.id');
        $m_news=M("Product");
        $map['id']=$id;
        $status=$m_news->where($map)->getField('status');
        $data['status']=abs($status-1);
        $statusArr = array("待审核", "已发布");
        if($m_news->where($map)->save($data)){
            $this->ajaxReturn(array("status" => 1, "info" => $statusArr[$data['status']]));
            //echo '<img src="../Public/Img/action_'.$data['is_recommend'].'.png" border="0">';
            exit;
        }
        return false;
    }
    
    

//     public function changePhoneStatus(){
//         $id=I('get.id');
//         $m_news=M("Product");
//         $map['id']=$id;
//         $status=$m_news->where($map)->getField('wap_display');
//         $data['wap_display']=abs($status-1);
//         if($m_news->where($map)->save($data)){
//             $this->ajaxReturn(array("status" => 1, "info" => '<img src="'.__ROOT__.'/Public/Img/iphone-'.$data['wap_display'].'.png" border="0">'));
//             //echo '<img src="../Public/Img/action_'.$data['is_recommend'].'.png" border="0">';
//             exit;
//         }
//         return false;
//     }
    
    
    //       再次对这个过时的后台设计表示无语和无力，谁让俺是接盘侠---------by ek_熊
    
    //     public function category() {
    
    //         if (IS_POST) {
    //             $this->ajaxReturn(D("Product")->category());
    //         } else {
    //             $this->assign("list", D("Product")->category());
    //             $this->display();
    //         }
    //     }
    
    
    
    //       别怪我，你实在是是太丑了，我忍不了---------by ek_熊
    
    //        public function index() {
    
    //         $M = M("Product");
    //         //过滤
    //         $s=array('0','1');
    //         $map=array();
    //         if($title=I('get.title'))$map['title']=array('like',"%{$title}%");
    //         if(in_array(I('get.status'),$s))$map['status']=I('get.status');
    //         if($cid=I('get.cid'))$map['cid']=$cid;
    //         if(in_array(I('get.is_recommend'),$s))$map['is_recommend']=I('get.is_recommend');
    //         //
    //         $count = $M->where($map)->count();
    
    //         $page = new \Think\Page($count, 20);
    //         $showPage = $page->show();
    //         $this->assign("page", $showPage);
    //         $this->assign("list", D("Product")->listProduct($page->firstRow, $page->listRows,$map));
    //         $this->display();
    //     }
    

    //     public function changeAttr(){
    //         $id=I('get.id');
    //         $m_news=M("Product");
    //         $map['id']=$id;
    //         $is_recommend=$m_news->where($map)->getField('is_recommend');
    //         $data['is_recommend']=abs($is_recommend-1);
    //         if($m_news->where($map)->save($data)){
    //             $this->ajaxReturn(array("status" => 1, "info" => '<img src="'.__ROOT__.'/Public/Img/action_'.$data['is_recommend'].'.png" border="0">'));
    //             //echo '<img src="../Public/Img/action_'.$data['is_recommend'].'.png" border="0">';
    //             exit;
    //         }
    //         return false;
    //     }

}